// ignore_for_file: prefer_interpolation_to_compose_strings

/*
 * @Author: CodeHare
 * @Date: 2023-10-30 11:34:54
 * @LastEditors: CodeHare
 * @LastEditTime: 2023-12-25 11:57:42
 * @Description: EMS参数设置之交流器设置
 */
import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/brn/brn_bottom_button_panel.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/ems_params_setting_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/widgets/converter_set_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_set_interface.dart';
import 'package:yt_devops/pages/site/site_setting/site_setting_base_info/widgets/item_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

class ConverterSetWidget extends StatefulWidget {
  /// 设备ID
  final String deviceId;

  const ConverterSetWidget(this.deviceId, {super.key});

  @override
  State<ConverterSetWidget> createState() => _ConverterSetWidgetState();
}

class _ConverterSetWidgetState extends State<ConverterSetWidget> {
  var converterProtectionParameterList =
      ConverterSetModel().converterProtectionParameterList;
  var converterGridParameterSettingList =
      ConverterSetModel().converterGridParameterSettingList;
  bool isCanEdit = false;
  int setParamClickIndex = 0;
  EmsParamsSettingController paramsSetController =
      Get.find<EmsParamsSettingController>();
  late SettingReqParams requestParams;

  /// 网络状态
  ConnectStatusType? connectStatus = ConnectStatusType.off;

  /// 订阅在线状态数据流
  UseSubsribe emsOnlineStatusSubsribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? emsOnlineStatusSubscription;
  late Stream<Map<String, dynamic>> emsOnlineStatusBroadcastStream;

  /// 订阅指令值数据流
  UseSubsribe emsValSubscribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? emsValSubscription;
  late Stream<Map<String, dynamic>> emsValBroadcastStream;
  late Map socketMap = {};

  @override
  void initState() {
    super.initState();

    _listenEmsOnlineStatusValue();
    _listenEmsControlValue();
  }

  /// 监听EMS设备在线状态
  void _listenEmsOnlineStatusValue() {
    emsOnlineStatusBroadcastStream = emsOnlineStatusSubsribe
        .start([int.parse(widget.deviceId)], true,
            type: MessageEventType.networkStatus)
        .stream
        .asBroadcastStream();

    emsOnlineStatusSubscription = emsOnlineStatusBroadcastStream.listen((data) {
      if (data['networkStatus'] != null) {
        connectStatus = $enumDecodeNullable(
          $ConnectStatusTypeEnumMap,
          data['networkStatus'],
        );
      }
    });
  }

  /// 监听EMS指令值
  void _listenEmsControlValue() {
    emsValBroadcastStream = emsValSubscribe
        .start([int.parse(widget.deviceId)], true)
        .stream
        .asBroadcastStream();

    showLoading(toast: ResKey.loading.tr);
    emsValSubscription = emsValBroadcastStream.listen(
      (data) {
        socketMap = data;
        if (isCanEdit) return;

        socketMap.forEach(
          (key, value) {
            String originData = value.toString();

            if (key == 'generalChargingPowerLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[1].textEditingController?.text =
                  originData;
            } else if (key == 'severeChargingPowerLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[2].textEditingController?.text =
                  originData;
            } else if (key == 'generalInverterPowerLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[3].textEditingController?.text =
                  originData;
            } else if (key == 'severeInverterPowerLimitation') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[4].textEditingController?.text =
                  originData;
            } else if (key == 'converterGeneralOvervoltageLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[5].textEditingController?.text =
                  originData;
            } else if (key == 'converterSevereOvervoltageLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[6].textEditingController?.text =
                  originData;
            } else if (key == 'converterGeneralUndervoltageLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[7].textEditingController?.text =
                  originData;
            } else if (key == 'converterSevereUndervoltageLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[8].textEditingController?.text =
                  originData;
            } else if (key == 'converterGeneralChargingCurrentLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[9].textEditingController?.text =
                  originData;
            } else if (key == 'converterSevereChargingCurrentLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[10].textEditingController?.text =
                  originData;
            } else if (key == 'generalInverterCurrentLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[11].textEditingController?.text =
                  originData;
            } else if (key == 'severeInverterCurrentLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[12].textEditingController?.text =
                  originData;
            } else if (key == 'converterGeneralOverTemperatureLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[13].textEditingController?.text =
                  originData;
            } else if (key == 'converterSevereOverTemperatureLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[14].textEditingController?.text =
                  originData;
            } else if (key == 'converterGeneralLowTemperatureLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[15].textEditingController?.text =
                  originData;
            } else if (key == 'converterSevereLowTemperatureLimit') {
              Log.d("===$key的具体值====$originData");
              converterProtectionParameterList[16].textEditingController?.text =
                  originData;
            } else if (key == 'antiBackflowThreshold') {
              Log.d("===$key的具体值====$originData");
              converterGridParameterSettingList[1].textEditingController?.text =
                  originData;
            } else if (key == 'maximumLoadOfTransformer') {
              Log.d("===$key的具体值====$originData");
              converterGridParameterSettingList[2].textEditingController?.text =
                  originData;
            }
          },
        );

        dismissLoading();
        setState(() {});
      },
    );
  }

  Container _generateListHeader(item, int index) {
    //增加index来标记点击了那个参数设置
    return Container(
      height: 53,
      padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 0),
      alignment: Alignment.center,
      color: Colour.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            item.label,
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: Colour.mainTextColor,
            ),
          ),
          Visibility(
              visible: !isCanEdit,
              child: GestureDetector(
                onTap: () {
                  if (connectStatus == ConnectStatusType.off) return;

                  setParamClickIndex = index;
                  setState(() {
                    isCanEdit = true;
                  });
                },
                child: Text(
                  item.unit,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colour.primaryColor,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              )),
        ],
      ),
    );
  }

  ///变流器保护参数设置
  Map<String, dynamic>? _collectInstructParams() {
    requestParams = SettingReqParams(
      deviceId: widget.deviceId,
      input: {
        "generalChargingPowerLimit":
            converterProtectionParameterList[1].textEditingController?.text ??
                '--',
        "severeChargingPowerLimit":
            converterProtectionParameterList[2].textEditingController?.text ??
                '--',
        "generalInverterPowerLimit":
            converterProtectionParameterList[3].textEditingController?.text ??
                '--',
        "severeInverterPowerLimitation":
            converterProtectionParameterList[4].textEditingController?.text ??
                '--',
        "converterGeneralOvervoltageLimit":
            converterProtectionParameterList[5].textEditingController?.text ??
                '--', // 0
        "converterSevereOvervoltageLimit":
            converterProtectionParameterList[6].textEditingController?.text ??
                '--', // 0
        "converterGeneralUndervoltageLimit":
            converterProtectionParameterList[7].textEditingController?.text ??
                '--', // 0
        "converterSevereUndervoltageLimit":
            converterProtectionParameterList[8].textEditingController?.text ??
                '--', // 0
        "converterGeneralChargingCurrentLimit":
            converterProtectionParameterList[9].textEditingController?.text ??
                '--',
        "converterSevereChargingCurrentLimit":
            converterProtectionParameterList[10].textEditingController?.text ??
                '--', // 0
        "generalInverterCurrentLimit":
            converterProtectionParameterList[11].textEditingController?.text ??
                '--',
        "severeInverterCurrentLimit":
            converterProtectionParameterList[12].textEditingController?.text ??
                '--',
        "converterGeneralOverTemperatureLimit":
            converterProtectionParameterList[13].textEditingController?.text ??
                '--', // 0
        "converterSevereOverTemperatureLimit":
            converterProtectionParameterList[14].textEditingController?.text ??
                '--', // 0
        "converterGeneralLowTemperatureLimit":
            converterProtectionParameterList[15].textEditingController?.text ??
                '--', // 0
        "converterSevereLowTemperatureLimit":
            converterProtectionParameterList[16].textEditingController?.text ??
                '--', // 0
      },
    );

    return ConverterProtectionParameterSettings().trigger(
      widget.deviceId,
      requestParams,
    );
  }

  ///电网参数设置
  Map<String, dynamic>? _setElectricityParams() {
    requestParams = SettingReqParams(
      deviceId: widget.deviceId,
      input: {
        "antiBackflowThreshold":
            converterGridParameterSettingList[1].textEditingController?.text ??
                '--',
        "maximumLoadOfTransformer":
            converterGridParameterSettingList[2].textEditingController?.text ??
                '--',
      },
    );

    return ConverterGridParameterSettings().trigger(
      widget.deviceId,
      requestParams,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Visibility(
                  visible: !(isCanEdit && setParamClickIndex == 1),
                  child: Container(
                    height: 850,
                    color: Colour.white,
                    margin: const EdgeInsets.only(top: 10),
                    child: ListView.separated(
                      physics: const NeverScrollableScrollPhysics(),
                      padding: EdgeInsets.zero,
                      itemBuilder: (context, index) {
                        final item = converterProtectionParameterList[index];

                        if (index == 0) {
                          return _generateListHeader(item, 0);
                        } else {
                          return SizedBox(
                            // padding: EdgeInsets.fromLTRB(16.w, 0, 0, 0),
                            child: ItemWidget(
                              item.label,
                              item.textEditingController,
                              isRequired: isCanEdit,
                              isCanEdit: isCanEdit,
                              unitString: item.unit,
                              hintString: isCanEdit ? ResKey.plsInput.tr : '',
                              titleColor: Colour.lightTextColor,
                              unitTextColor:
                                  connectStatus == ConnectStatusType.off
                                      ? Colour.offlineTextColor
                                      : Colour.mainTextColor,
                              inputTextColor:
                                  connectStatus == ConnectStatusType.off
                                      ? Colour.offlineTextColor
                                      : Colour.mainTextColor,
                              titleFont: 14,
                              isShowDivider: false,
                            ),
                          );
                        }
                      },
                      separatorBuilder: (BuildContext context, int index) =>
                          Divider(
                        color: Colour.dividerColor,
                        height: 1,
                        indent: 16.w,
                        endIndent: 16.w,
                      ),
                      itemCount: converterProtectionParameterList.length,
                    ),
                  ),
                ),
                Visibility(
                    visible: !(isCanEdit && setParamClickIndex == 0),
                    child: Container(
                      margin: const EdgeInsets.only(top: 10),
                      height: 153,
                      child: ListView.separated(
                        padding: EdgeInsets.zero,
                        physics: const NeverScrollableScrollPhysics(),
                        itemBuilder: (context, index) {
                          final item = converterGridParameterSettingList[index];
                          if (index == 0) {
                            return _generateListHeader(item, 1);
                          } else {
                            return Container(
                              color: Colour.white,
                              // padding: EdgeInsets.fromLTRB(16.w, 0, 0, 0),
                              child: ItemWidget(
                                item.label,
                                item.textEditingController,
                                isRequired: isCanEdit,
                                isCanEdit: isCanEdit,
                                unitString: item.unit,
                                hintString: isCanEdit ? ResKey.plsInput.tr : '',
                                titleColor: Colour.lightTextColor,
                                unitTextColor:
                                    connectStatus == ConnectStatusType.off
                                        ? Colour.offlineTextColor
                                        : Colour.mainTextColor,
                                inputTextColor:
                                    connectStatus == ConnectStatusType.off
                                        ? Colour.offlineTextColor
                                        : Colour.mainTextColor,
                                titleFont: 14,
                                isShowDivider: false,
                              ),
                            );
                          }
                        },
                        separatorBuilder: (BuildContext context, int index) =>
                            Divider(
                          color: Colour.dividerColor,
                          height: 1,
                          indent: 16.w,
                          endIndent: 16.w,
                        ),
                        itemCount: converterGridParameterSettingList.length,
                      ),
                    )),
              ],
            ),
          ),
        ),
        Visibility(
          visible: isCanEdit,
          child: Align(
            alignment: Alignment.bottomCenter,
            child: YtBrnBottomButtonPanel(
              mainButtonName: ResKey.deviceSendCommand.tr,
              mainButtonOnTap: () {
                if (!_checkCanSubmit()) {
                  showError('请填写所有必填选项');
                  return;
                }

                if (setParamClickIndex == 0) {
                  //电流器保护参数设置
                  Log.d('电流器保护参数设置下发参数');
                  var params = _collectInstructParams();
                  Log.d('params==' + params.toString());
                  BrnDialogManager.showConfirmDialog(
                    context,
                    cancel: ResKey.cancel.tr,
                    confirm: ResKey.sure.tr,
                    title: '是否确认下发参数',
                    onCancel: () => Get.back(),
                    onConfirm: () {
                      Log.d('params==' + params.toString());

                      /// 下发指令
                      paramsSetController
                          .sendCommand(context, params)
                          .then((value) {
                        Get.back();
                        isCanEdit = false;
                        setState(() {});
                      });
                    },
                  );
                } else if (setParamClickIndex == 1) {
                  //电网参数设置
                  Log.d('电网参数设置下发参数');
                  var params = _setElectricityParams();
                  BrnDialogManager.showConfirmDialog(
                    context,
                    cancel: ResKey.cancel.tr,
                    confirm: ResKey.sure.tr,
                    title: '是否确认下发参数',
                    onCancel: () => Get.back(),
                    onConfirm: () {
                      Log.d('params==' + params.toString());

                      /// 下发指令
                      paramsSetController
                          .sendCommand(context, params)
                          .then((value) {
                        Get.back();
                        isCanEdit = false;
                        setState(() {});
                      });
                    },
                  );
                }
              },
              secondaryButtonName: ResKey.cancel.tr,
              secondaryButtonBorder: Border.all(
                color: Colour.dividerColor,
              ),
              secondaryButtonOnTap: () {
                setState(() {
                  isCanEdit = false;
                });
              },
            ),
          ),
        ),
      ],
    );
  }

  bool _checkCanSubmit() {
    if (setParamClickIndex == 0) {
      for (int i = 1; i < converterProtectionParameterList.length; i++) {
        TextEditingController? textEditingController =
            converterProtectionParameterList[i].textEditingController;
        if (textEditingController!.text.isEmpty) {
          return false;
        }
      }
      return true;
    } else if (setParamClickIndex == 1) {
      TextEditingController? textEditingController1 =
          converterGridParameterSettingList[1].textEditingController;
      TextEditingController? textEditingController2 =
          converterGridParameterSettingList[2].textEditingController;
      if (textEditingController1 != null &&
          textEditingController1.text.isNotEmpty &&
          textEditingController2 != null &&
          textEditingController2.text.isNotEmpty) {
        return true;
      } else {
        return false;
      }
    }
    return false;
  }

  @override
  dispose() {
    emsOnlineStatusSubscription?.cancel();
    emsOnlineStatusSubsribe.closeListen();
    emsValSubscription?.cancel();
    emsValSubscribe.closeListen();

    super.dispose();
  }
}
